<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../react18/react.development.js"></script>
    <script src="../react18/react-dom.development.js"></script>
    <script src="../react18/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      class Message extends React.Component {
        state = {
          opacity: 1,
          timer: null,
          color: "red",
        };

        //组件挂载完成的生命周期函数
        componentDidMount() {
          let { opacity, color } = this.state;
          //先使用一个变量保存当前的timerID
          var timer = setInterval(() => {
            opacity -= 0.03;
            if (opacity <= 0) {
              opacity = 1;
            }
            this.setState({ opacity: opacity });

            console.log(opacity);
          }, 10);

          //然后使用setState的方法把当前的timerID设置给状态中,让其他函数内部共享当前的timerID
          this.setState({ timer: timer });
        }

        render() {
          return (
            <div>
              <h2
                style={{ opacity: this.state.opacity, color: this.state.color }}
              >
                React真的有点难,怎么办?????
              </h2>
            </div>
          );
        }

        //当组件被销毁前 立马会执行当前的函数
        componentWillUnmount() {
          const { timer } = this.state;
          console.log("马上就要销毁我了");
          console.log(timer, "********");
          clearInterval(timer);
        }
      }

      class App extends React.Component {
        state = {
          isStudyReact: true,
        };
        render() {
          const { isStudyReact } = this.state;
          return (
            <div>
              {isStudyReact ? <Message /> : ""}
              <button onClick={this.changeStudyState}>
                {isStudyReact ? "我不学了!!!!" : "我决定还是学吧!!!!"}
              </button>
            </div>
          );
        }

        changeStudyState = () => {
          const { isStudyReact } = this.state;
          this.setState({ isStudyReact: !isStudyReact });
        };
      }

      ReactDOM.createRoot(document.getElementById("app")).render(<App />);
    </script>
  </body>
</html>
